<?php
session_start();
require_once '../includes/config.php';
require_once '../includes/database.php';
require_once '../includes/auth.php';
require_once '../includes/attendance_manager.php';
require_once '../includes/user.php';

// 检查权限
$auth = getAuth();
$auth->requirePermission('super_admin');

// 获取当前用户信息
$currentUser = $auth->getCurrentUser();

// 初始化数据库和考勤管理器
$database = getDatabaseConnection();
$attendanceManager = new AttendanceManager($database);
$userManager = new UserManager($database);

// 处理GET参数的消息
if (isset($_GET['message']) && isset($_GET['messageType'])) {
    $message = $_GET['message'];
    $messageType = $_GET['messageType'];
} else {
    $message = '';
    $messageType = '';
}

// 处理表单提交
if ($_POST) {
    $action = $_POST['action'] ?? '';
    
    try {
        switch ($action) {
            case 'add_record':
                // 检查记录是否已存在
                if ($attendanceManager->recordExists($_POST['user_id'], $_POST['record_date'])) {
                    throw new Exception('该用户当天的考勤记录已存在');
                }
                
                $recordData = [
                    'user_id' => $_POST['user_id'],
                    'record_date' => $_POST['record_date'],
                    'status' => $_POST['status'],
                    'notes' => $_POST['notes']
                ];
                
                // 所有状态都使用相同的时间字段
                $recordData['morning_clock_in'] = $_POST['morning_clock_in'] ?? null;
                $recordData['morning_clock_out'] = $_POST['morning_clock_out'] ?? null;
                $recordData['afternoon_clock_in'] = $_POST['afternoon_clock_in'] ?? null;
                $recordData['afternoon_clock_out'] = $_POST['afternoon_clock_out'] ?? null;
                
                if ($attendanceManager->addAttendanceRecord($recordData)) {
                    // 重定向到当前页面，清除POST数据
                    header('Location: attendance_enhanced.php?message=考勤记录添加成功&messageType=success');
                    exit;
                } else {
                    throw new Exception('添加考勤记录失败');
                }
                break;
                
            case 'edit_record':
                $recordId = $_POST['record_id'];
                // 检查记录是否已存在（排除当前记录）
                if ($attendanceManager->recordExists($_POST['user_id'], $_POST['record_date'], $recordId)) {
                    throw new Exception('该用户当天的考勤记录已存在');
                }
                
                $recordData = [
                    'user_id' => $_POST['user_id'],
                    'record_date' => $_POST['record_date'],
                    'status' => $_POST['status'],
                    'notes' => $_POST['notes']
                ];
                
                // 所有状态都使用相同的时间字段
                $recordData['morning_clock_in'] = $_POST['morning_clock_in'] ?? null;
                $recordData['morning_clock_out'] = $_POST['morning_clock_out'] ?? null;
                $recordData['afternoon_clock_in'] = $_POST['afternoon_clock_in'] ?? null;
                $recordData['afternoon_clock_out'] = $_POST['afternoon_clock_out'] ?? null;
                
                if ($attendanceManager->updateAttendanceRecord($recordId, $recordData)) {
                    // 重定向到当前页面，清除POST数据
                    header('Location: attendance_enhanced.php?message=考勤记录更新成功&messageType=success');
                    exit;
                } else {
                    throw new Exception('更新考勤记录失败');
                }
                break;
                
            case 'delete_record':
                $recordId = $_POST['record_id'];
                if ($attendanceManager->deleteAttendanceRecord($recordId)) {
                    // 重定向到当前页面，清除POST数据
                    header('Location: attendance_enhanced.php?message=考勤记录删除成功&messageType=success');
                    exit;
                } else {
                    throw new Exception('删除考勤记录失败');
                }
                break;
                
            case 'batch_import':
                // 处理Excel导入
                if (isset($_FILES['import_file']) && $_FILES['import_file']['error'] === UPLOAD_ERR_OK) {
                    $importResult = $attendanceManager->importFromExcel($_FILES['import_file']['tmp_name']);
                    if ($importResult['success']) {
                        $message = 'Excel导入成功，共导入 ' . $importResult['imported'] . ' 条记录';
                        $messageType = 'success';
                    } else {
                        throw new Exception('Excel导入失败: ' . $importResult['error']);
                    }
                } else {
                    throw new Exception('请选择要导入的文件');
                }
                break;
        }
    } catch (Exception $e) {
        $message = $e->getMessage();
        $messageType = 'danger';
    }
}

// 获取查询参数
$search = $_GET['search'] ?? '';
$startDate = $_GET['start_date'] ?? '';
$endDate = $_GET['end_date'] ?? '';
$status = $_GET['status'] ?? '';
$userId = $_GET['user_id'] ?? '';

// 构建过滤器
$filters = [];
if ($search) $filters['search'] = $search;
if ($startDate) $filters['start_date'] = $startDate;
if ($endDate) $filters['end_date'] = $endDate;
if ($status) $filters['status'] = $status;
if ($userId) $filters['user_id'] = $userId;

// 获取所有考勤记录（不分页）
$recordsData = $attendanceManager->getAttendanceRecords(1, 10000, $filters); // 使用大数字获取所有记录
$records = $recordsData['records'];
$total = $recordsData['total'];

// 获取用户列表（用于筛选）
$users = $attendanceManager->getUsersForSelect();

// 获取考勤统计
$attendanceStats = $attendanceManager->getAttendanceStats($startDate, $endDate);
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>考勤管理 - 考勤管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
</head>
<body>
    <!-- 侧边栏 -->
    <?php include_once '../includes/sidebar.php'; ?>

    <!-- 主内容区 -->
    <div class="main-content">
        <!-- 顶部导航 -->
        <nav class="navbar navbar-expand navbar-custom mb-4">
            <div class="container-fluid">
                <div class="navbar-nav me-auto">
                    <span class="navbar-text">
                        <i class="fas fa-clipboard-list me-2"></i>考勤管理（增强版）
                    </span>
                </div>
                <div class="navbar-nav">
                    <span class="navbar-text me-3">
                        <i class="fas fa-user me-2"></i>
                        <?php echo htmlspecialchars($currentUser['full_name']); ?>
                    </span>
                    <a href="../user/profile.php" class="nav-link">
                        <i class="fas fa-cog"></i> 个人设置
                    </a>
                </div>
            </div>
        </nav>

        <?php if ($message): ?>
            <div class="alert alert-<?php echo $messageType; ?> alert-dismissible fade show" role="alert">
                <i class="fas fa-<?php echo $messageType === 'success' ? 'check' : 'exclamation-triangle'; ?> me-2"></i>
                <?php echo htmlspecialchars($message); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <!-- 考勤统计卡片 -->
        <div class="row mb-4">
            <div class="col-md-2">
                <div class="card bg-primary text-white">
                    <div class="card-body text-center">
                        <h4><?php echo $attendanceStats['total_records']; ?></h4>
                        <p class="mb-0">总记录数</p>
                    </div>
                </div>
            </div>
            <div class="col-md-2">
                <div class="card bg-success text-white">
                    <div class="card-body text-center">
                        <h4><?php echo $attendanceStats['normal_count']; ?></h4>
                        <p class="mb-0">正常</p>
                    </div>
                </div>
            </div>
            <div class="col-md-2">
                <div class="card bg-warning text-white">
                    <div class="card-body text-center">
                        <h4><?php echo $attendanceStats['late_count']; ?></h4>
                        <p class="mb-0">迟到</p>
                    </div>
                </div>
            </div>
            <div class="col-md-2">
                <div class="card bg-danger text-white">
                    <div class="card-body text-center">
                        <h4><?php echo $attendanceStats['early_leave_count']; ?></h4>
                        <p class="mb-0">早退</p>
                    </div>
                </div>
            </div>
            <div class="col-md-2">
                <div class="card bg-secondary text-white">
                    <div class="card-body text-center">
                        <h4><?php echo $attendanceStats['absent_count']; ?></h4>
                        <p class="mb-0">缺勤</p>
                    </div>
                </div>
            </div>
            <div class="col-md-2">
                <div class="card bg-info text-white">
                    <div class="card-body text-center">
                        <h4><?php echo number_format($attendanceStats['avg_work_hours'], 1); ?></h4>
                        <p class="mb-0">平均工时</p>
                    </div>
                </div>
            </div>
        </div>

        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="card-title mb-0">
                    <i class="fas fa-clipboard-list me-2"></i>考勤记录列表
                </h5>
                <div>
                    <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addRecordModal">
                        <i class="fas fa-plus me-2"></i>添加记录
                    </button>
                    <button class="btn btn-success btn-sm ms-2" data-bs-toggle="modal" data-bs-target="#batchAddModal">
                        <i class="fas fa-batch-sync me-2"></i>批量添加
                    </button>
                    <button class="btn btn-warning btn-sm ms-2" data-bs-toggle="modal" data-bs-target="#batchImportModal">
                        <i class="fas fa-file-import me-2"></i>Excel导入
                    </button>
                    <a href="download_template.php" class="btn btn-outline-secondary btn-sm ms-2">
                        <i class="fas fa-download me-2"></i>下载模板
                    </a>
                    <a href="calendar_view.php" class="btn btn-info btn-sm ms-2">
                        <i class="fas fa-calendar-alt me-2"></i>日历视图
                    </a>
                </div>
            </div>
            <div class="card-body">
                <!-- 筛选表单 -->
                <form method="get" class="mb-4">
                    <div class="row g-3">
                        <div class="col-md-3">
                            <label class="form-label">搜索</label>
                            <input type="text" name="search" class="form-control" placeholder="用户名、姓名、部门..." 
                                   value="<?php echo htmlspecialchars($search); ?>">
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">开始日期</label>
                            <input type="date" name="start_date" class="form-control" value="<?php echo htmlspecialchars($startDate); ?>">
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">结束日期</label>
                            <input type="date" name="end_date" class="form-control" value="<?php echo htmlspecialchars($endDate); ?>">
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">用户</label>
                            <select name="user_id" class="form-select">
                                <option value="">全部用户</option>
                                <?php foreach ($users as $user): ?>
                                    <option value="<?php echo $user['id']; ?>" <?php echo $userId == $user['id'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($user['full_name'] . ' (' . $user['username'] . ')'); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">状态</label>
                            <select name="status" class="form-select">
                                <option value="">全部状态</option>
                                <option value="normal" <?php echo $status === 'normal' ? 'selected' : ''; ?>>正常</option>
                                <option value="late" <?php echo $status === 'late' ? 'selected' : ''; ?>>迟到</option>
                                <option value="early_leave" <?php echo $status === 'early_leave' ? 'selected' : ''; ?>>早退</option>
                                <option value="absent" <?php echo $status === 'absent' ? 'selected' : ''; ?>>缺勤</option>
                                <option value="leave" <?php echo $status === 'leave' ? 'selected' : ''; ?>>请假</option>
                                <option value="business_trip" <?php echo $status === 'business_trip' ? 'selected' : ''; ?>>出差</option>
                                <option value="overtime" <?php echo $status === 'overtime' ? 'selected' : ''; ?>>加班</option>
                            </select>
                        </div>
                        <div class="col-md-1 d-flex align-items-end">
                            <button type="submit" class="btn btn-primary w-100">筛选</button>
                        </div>
                    </div>
                </form>

                <!-- 批量操作工具栏 -->
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" id="selectAllRecords">
                        <label class="form-check-label" for="selectAllRecords">全选</label>
                    </div>
                    <div>
                        <button class="btn btn-danger btn-sm" id="batchDeleteBtn" disabled onclick="batchDeleteRecords()">
                            <i class="fas fa-trash me-2"></i>批量删除
                        </button>
                        <span class="text-muted ms-2" id="selectedCount">已选择 0 条记录</span>
                    </div>
                </div>

                <!-- 表格内容 -->
                <?php if (empty($records)): ?>
                    <div class="text-center text-muted py-5">
                        <i class="fas fa-clipboard-list fa-4x mb-3"></i>
                        <h4>暂无考勤记录</h4>
                        <p>点击"添加记录"按钮创建第一条考勤记录</p>
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead>
                                <tr>
                                    <th><input type="checkbox" id="selectAllTable"></th>
                                    <th>序号</th>
                                    <th>用户</th>
                                    <th>部门</th>
                                    <th>日期</th>
                                    <th>上午上班</th>
                                    <th>上午下班</th>
                                    <th>下午上班</th>
                                    <th>下午下班</th>
                                    <th>全天工时</th>
                                    <th>总工时</th>
                                    <th>状态</th>
                                    <th>备注</th>
                                    <th>创建时间</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php 
                                // 计算起始序号
                                $currentNumber = 1;
                                ?>
                                <?php foreach ($records as $record): ?>
                                    <tr>
                                        <td><input type="checkbox" class="record-checkbox" value="<?php echo $record['id']; ?>"></td>
                                        <td><?php echo $currentNumber++; ?></td>
                                        <td><?php echo htmlspecialchars($record['full_name']); ?></td>
                                        <td><?php echo htmlspecialchars($record['department']); ?></td>
                                        <td><?php echo $record['record_date']; ?></td>
                                        <td><?php echo $record['morning_clock_in'] ?: '-'; ?></td>
                                        <td><?php echo $record['morning_clock_out'] ?: '-'; ?></td>
                                        <td><?php echo $record['afternoon_clock_in'] ?: '-'; ?></td>
                                        <td><?php echo $record['afternoon_clock_out'] ?: '-'; ?></td>
                                        <td><?php echo $record['all_day_work_hours'] ? number_format($record['all_day_work_hours'], 1) . '小时' : '-'; ?></td>
                                        <td><?php echo $record['total_work_hours'] ? number_format($record['total_work_hours'], 1) . '小时' : '-'; ?></td>
                                        <td>
                                            <?php
                                            $statusBadge = [
                                                'normal' => ['label' => '正常', 'class' => 'bg-success'],
                                                'late' => ['label' => '迟到', 'class' => 'bg-warning'],
                                                'early_leave' => ['label' => '早退', 'class' => 'bg-danger'],
                                                'absent' => ['label' => '缺勤', 'class' => 'bg-secondary'],
                                                'leave' => ['label' => '请假', 'class' => 'bg-info'],
                                                'business_trip' => ['label' => '出差', 'class' => 'bg-primary'],
                                                'overtime' => ['label' => '加班', 'class' => 'bg-dark']
                                            ];
                                            $statusInfo = $statusBadge[$record['status']] ?? ['label' => '未知', 'class' => 'bg-dark'];
                                            ?>
                                            <span class="badge <?php echo $statusInfo['class']; ?>">
                                                <?php echo $statusInfo['label']; ?>
                                            </span>
                                        </td>
                                        <td><?php echo htmlspecialchars($record['notes'] ?: '-'); ?></td>
                                        <td><?php echo date('Y-m-d H:i', strtotime($record['created_at'])); ?></td>
                                        <td>
                                            <div class="btn-group btn-group-sm">
                                                <button class="btn btn-outline-primary" 
                                                        data-bs-toggle="modal" 
                                                        data-bs-target="#editRecordModal"
                                                        onclick="loadRecordData(<?php echo $record['id']; ?>)">
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                                <button class="btn btn-outline-danger" 
                                                        onclick="confirmDelete(<?php echo $record['id']; ?>, '<?php echo htmlspecialchars($record['full_name']); ?> - <?php echo $record['record_date']; ?>')">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>

                <?php endif; ?>

                <!-- 记录统计 -->
                <?php if ($total > 0): ?>
                <div class="d-flex justify-content-between align-items-center mt-4">
                    <div class="text-muted">
                        共 <?php echo $total; ?> 条记录
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- 添加考勤记录模态框 -->
    <div class="modal fade" id="addRecordModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <form method="post" id="addRecordForm">
                    <div class="modal-header">
                        <h5 class="modal-title">添加考勤记录</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" name="action" value="add_record">
                        <div class="mb-3">
                            <label class="form-label">用户 *</label>
                            <select name="user_id" class="form-select" required>
                                <option value="">选择用户</option>
                                <?php foreach ($users as $user): ?>
                                    <option value="<?php echo $user['id']; ?>">
                                        <?php echo htmlspecialchars($user['full_name'] . ' (' . $user['username'] . ') - ' . $user['department']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">日期 *</label>
                            <input type="date" name="record_date" class="form-control" value="<?php echo date('Y-m-d'); ?>" required>
                        </div>
                        
                        <!-- 状态选择 -->
                        <div class="mb-3">
                            <label class="form-label">状态 *</label>
                            <select name="status" class="form-select" id="statusSelect" required onchange="toggleTimeSections()">
                                <option value="normal" selected>正常</option>
                                <option value="late">迟到</option>
                                <option value="early_leave">早退</option>
                                <option value="absent">缺勤</option>
                                <option value="leave">请假</option>
                                <option value="business_trip">出差</option>
                                <option value="overtime">加班</option>
                            </select>
                        </div>
                        
                        <!-- 正常状态的时间记录 -->
                        <div id="normalTimeSection">
                            <div class="time-section">
                                <h6><i class="fas fa-sun me-2"></i>上午记录</h6>
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">上班时间</label>
                                            <input type="time" name="morning_clock_in" class="form-control" value="08:30">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">下班时间</label>
                                            <input type="time" name="morning_clock_out" class="form-control" value="12:00">
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="time-section">
                                <h6><i class="fas fa-moon me-2"></i>下午记录</h6>
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">上班时间</label>
                                            <input type="time" name="afternoon_clock_in" class="form-control" value="14:00">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">下班时间</label>
                                            <input type="time" name="afternoon_clock_out" class="form-control" value="18:30">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 出差状态的时间记录 -->
                        <div id="businessTripSection" style="display: none;">
                            <div class="time-section">
                                <h6><i class="fas fa-plane me-2"></i>出差记录</h6>
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">上班时间</label>
                                            <input type="time" name="morning_clock_in" class="form-control" value="08:30">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">下班时间</label>
                                            <input type="time" name="morning_clock_out" class="form-control" value="12:00">
                                        </div>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">上班时间</label>
                                            <input type="time" name="afternoon_clock_in" class="form-control" value="14:00">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">下班时间</label>
                                            <input type="time" name="afternoon_clock_out" class="form-control" value="18:30">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">备注</label>
                            <textarea name="notes" class="form-control" rows="3"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="submit" class="btn btn-primary">添加记录</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 编辑考勤记录模态框 -->
    <div class="modal fade" id="editRecordModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <form method="post" id="editRecordForm">
                    <div class="modal-header">
                        <h5 class="modal-title">编辑考勤记录</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" name="action" value="edit_record">
                        <input type="hidden" name="record_id" id="edit_record_id">
                        <div class="mb-3">
                            <label class="form-label">用户 *</label>
                            <select name="user_id" id="edit_user_id" class="form-select" required>
                                <option value="">选择用户</option>
                                <?php foreach ($users as $user): ?>
                                    <option value="<?php echo $user['id']; ?>">
                                        <?php echo htmlspecialchars($user['full_name'] . ' (' . $user['username'] . ') - ' . $user['department']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">日期 *</label>
                            <input type="date" name="record_date" id="edit_record_date" class="form-control" required>
                        </div>
                        
                        <!-- 状态选择 -->
                        <div class="mb-3">
                            <label class="form-label">状态 *</label>
                            <select name="status" class="form-select" id="edit_statusSelect" required onchange="toggleEditTimeSections()">
                                <option value="normal">正常</option>
                                <option value="late">迟到</option>
                                <option value="early_leave">早退</option>
                                <option value="absent">缺勤</option>
                                <option value="leave">请假</option>
                                <option value="business_trip">出差</option>
                                <option value="overtime">加班</option>
                            </select>
                        </div>
                        
                        <!-- 正常状态的时间记录 -->
                        <div id="edit_normalTimeSection">
                            <div class="time-section">
                                <h6><i class="fas fa-sun me-2"></i>上午记录</h6>
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">上班时间</label>
                                            <input type="time" name="morning_clock_in" id="edit_morning_clock_in" class="form-control">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">下班时间</label>
                                            <input type="time" name="morning_clock_out" id="edit_morning_clock_out" class="form-control">
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="time-section">
                                <h6><i class="fas fa-moon me-2"></i>下午记录</h6>
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">上班时间</label>
                                            <input type="time" name="afternoon_clock_in" id="edit_afternoon_clock_in" class="form-control">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">下班时间</label>
                                            <input type="time" name="afternoon_clock_out" id="edit_afternoon_clock_out" class="form-control">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 出差状态的时间记录 -->
                        <div id="edit_businessTripSection" style="display: none;">
                            <div class="time-section">
                                <h6><i class="fas fa-plane me-2"></i>出差记录</h6>
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">上班时间</label>
                                            <input type="time" name="morning_clock_in" id="edit_morning_clock_in" class="form-control">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">下班时间</label>
                                            <input type="time" name="morning_clock_out" id="edit_morning_clock_out" class="form-control">
                                        </div>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">上班时间</label>
                                            <input type="time" name="afternoon_clock_in" id="edit_afternoon_clock_in" class="form-control">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">下班时间</label>
                                            <input type="time" name="afternoon_clock_out" id="edit_afternoon_clock_out" class="form-control">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">备注</label>
                            <textarea name="notes" id="edit_notes" class="form-control" rows="3"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="submit" class="btn btn-primary">保存修改</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 批量导入模态框 -->
    <div class="modal fade" id="batchImportModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <form method="post" enctype="multipart/form-data" id="batchImportForm">
                    <div class="modal-header">
                        <h5 class="modal-title">批量导入考勤记录</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" name="action" value="batch_import">
                        <div class="mb-3">
                            <label class="form-label">选择文件</label>
                            <input type="file" name="import_file" class="form-control" accept=".csv,.xlsx" required>
                            <div class="form-text">支持CSV和Excel格式文件</div>
                        </div>
                        <div class="mb-3">
                            <small class="text-muted">
                                <strong>文件格式要求：</strong><br>
                                用户名,日期(YYYY-MM-DD),状态,上午上班时间,上午下班时间,下午上班时间,下午下班时间,全天工时,备注<br>
                                <strong>状态可选：</strong>normal, late, early_leave, absent, leave, business_trip, overtime
                            </small>
                        </div>
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle me-2"></i>
                            建议先<a href="download_template.php" class="alert-link">下载模板文件</a>，按照模板格式填写数据后再导入。
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-upload me-2"></i>导入数据
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 删除考勤记录表单 -->
    <form id="deleteForm" method="post" style="display: none;">
        <input type="hidden" name="action" value="delete_record">
        <input type="hidden" name="record_id" id="delete_record_id">
    </form>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 切换时间区域显示
        function toggleTimeSections() {
            const status = document.getElementById('statusSelect').value;
            const normalSection = document.getElementById('normalTimeSection');
            const businessTripSection = document.getElementById('businessTripSection');
            
            if (status === 'business_trip') {
                normalSection.style.display = 'none';
                businessTripSection.style.display = 'block';
            } else {
                normalSection.style.display = 'block';
                businessTripSection.style.display = 'none';
            }
        }
        
        function toggleEditTimeSections() {
            const status = document.getElementById('edit_statusSelect').value;
            const normalSection = document.getElementById('edit_normalTimeSection');
            const businessTripSection = document.getElementById('edit_businessTripSection');
            
            if (status === 'business_trip') {
                normalSection.style.display = 'none';
                businessTripSection.style.display = 'block';
            } else {
                normalSection.style.display = 'block';
                businessTripSection.style.display = 'none';
            }
        }

        // 加载考勤记录数据到编辑模态框
        function loadRecordData(recordId) {
            fetch(`../api/get_attendance_record.php?id=${recordId}`)
                .then(response => response.json())
                .then(record => {
                    document.getElementById('edit_record_id').value = record.id;
                    document.getElementById('edit_user_id').value = record.user_id;
                    document.getElementById('edit_record_date').value = record.record_date;
                    document.getElementById('edit_statusSelect').value = record.status;
                    document.getElementById('edit_notes').value = record.notes || '';
                    
                    // 设置时间字段
                    document.getElementById('edit_morning_clock_in').value = record.morning_clock_in || '';
                    document.getElementById('edit_morning_clock_out').value = record.morning_clock_out || '';
                    document.getElementById('edit_afternoon_clock_in').value = record.afternoon_clock_in || '';
                    document.getElementById('edit_afternoon_clock_out').value = record.afternoon_clock_out || '';
                    document.getElementById('edit_all_day_work_hours').value = record.all_day_work_hours || '';
                    
                    // 切换时间区域显示
                    toggleEditTimeSections();
                })
                .catch(error => {
                    console.error('加载记录数据失败:', error);
                    alert('加载记录数据失败，请重试');
                });
        }

        // 确认删除记录
        function confirmDelete(recordId, recordInfo) {
            if (confirm(`确定要删除考勤记录 "${recordInfo}" 吗？`)) {
                document.getElementById('delete_record_id').value = recordId;
                document.getElementById('deleteForm').submit();
            }
        }

        // 批量删除记录
        function batchDeleteRecords() {
            const selectedRecords = document.querySelectorAll('.record-checkbox:checked');
            if (selectedRecords.length === 0) {
                alert('请选择要删除的记录');
                return;
            }
            
            if (confirm(`确定要删除选中的 ${selectedRecords.length} 条记录吗？`)) {
                const recordIds = Array.from(selectedRecords).map(checkbox => checkbox.value);
                // 这里需要实现批量删除的逻辑
                alert(`批量删除功能待实现，选中的记录ID: ${recordIds.join(', ')}`);
            }
        }


        // 初始化复选框事件
        document.addEventListener('DOMContentLoaded', function() {
            // 全选功能
            document.getElementById('selectAllRecords').addEventListener('change', function() {
                const checkboxes = document.querySelectorAll('.record-checkbox');
                checkboxes.forEach(checkbox => {
                    checkbox.checked = this.checked;
                });
                updateSelectedCount();
            });
            
            document.getElementById('selectAllTable').addEventListener('change', function() {
                const checkboxes = document.querySelectorAll('.record-checkbox');
                checkboxes.forEach(checkbox => {
                    checkbox.checked = this.checked;
                });
                updateSelectedCount();
            });
            
            // 监听复选框变化
            document.querySelectorAll('.record-checkbox').forEach(checkbox => {
                checkbox.addEventListener('change', updateSelectedCount);
            });
        });

        // 更新选中数量
        function updateSelectedCount() {
            const selected = document.querySelectorAll('.record-checkbox:checked').length;
            document.getElementById('selectedCount').textContent = '已选择 ' + selected + ' 条记录';
            document.getElementById('batchDeleteBtn').disabled = selected === 0;
        }

        // 如果需要自动刷新，取消注释下面这行
        // autoRefresh(30000); // 每30秒自动刷新
    </script>
</body>
</html>
